# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from urllib.parse import urlencode
from common.helper import Helper
from threading import Thread


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "E路阳光（DIY版）"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "days": ["1m", "3m", "6m", "9m", "1y"],
            "people_count": ["1"],
            "airplane_death": ["0", "100000", "200000", "500000", "1000000"],
            "train_death": ["0", "50000", "100000", "200000", "500000"],
            "ship_death": ["0", "50000", "100000", "200000", "500000"],
            "passenger_death": ["0", "10000", "20000", "50000", "100000", "200000"],
            "private_death": ["0", "10000", "20000", "100000", "200000"]
        }

        for v in product(plan["days"], plan["people_count"], plan["airplane_death"], plan["train_death"],
                         plan["ship_death"], plan["passenger_death"], plan["private_death"]):
            data = Helper.formatProductInfo(plan, v)
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):

        params = '''
        agentId: 
        sessionKey: myInsurance9ed330c5-e823-4964-a193-33a9e968bc37
        pagePropertyObj.selectedPlanId: 547
        pagePropertyObj.renewal: false
        pagePropertyObj.renewalCalendarStartDate: 
        pagePropertyObj.renewalCalendarEndDate: 
        source: 
        fuwu: 
        sso: true
        processId: buy-process-b53145c6-4e51-4b1b-977d-02404711c4dd
        orderSource: product-center
        platform: pc
        statisticProductType: 01
        statisticProductId: 542
        verifycode: 
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].clauseId: 13
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[0].liabilityId: 13
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[0].three: 
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[0].isSelected: true
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[0].amount: 100
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[1].liabilityId: 14
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[1].three: 
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[1].isSelected: true
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[1].amount: 50
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[2].liabilityId: 15
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[2].three: 
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[2].isSelected: true
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[2].amount: 10
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[3].liabilityId: 16
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[3].three: 
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[3].isSelected: true
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[3].amount: 20
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].clauseId: 14
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[0].liabilityId: 17
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[0].three: 
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[0].isSelected: true
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[0].amount: 10
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[1].liabilityId: 18
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[1].three: 
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[1].isSelected: true
        pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[1].amount: 10
        pagePropertyObj.insuPeriod: 12
        pagePropertyObj.insuStartDate: 2020-04-29
        pagePropertyObj.insuPeriodUnit: 02
        pagePropertyObj.insuEndDate: 2021-04-28
        '''
        data = Helper.perfectJson(params)
        if dt["private_death"] == "0":
            private_death = "0"
        else:
            private_death = "0.5" if dt["private_death"] == "10000" else str(
                int(1 / 2 * int(int(dt["private_death"]) / 10000)))
        if dt["days"] == "1m":
            endDate = "2020-05-28"
        elif dt["days"] == "3m":
            endDate = "2020-07-28"
        elif dt["days"] == "6m":
            endDate = "2020-10-28"
        elif dt["days"] == "9m":
            endDate = "2021-01-28"
        else:
            endDate = "2021-04-28"
        data["pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[0].amount"] = "0" if dt[
                                                                                                                 "airplane_death"] == "0" else  str(
            int(int(dt["airplane_death"]) / 10000))
        data["pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[1].amount"] = "0" if dt[
                                                                                                                 "train_death"] == "0" else str(
            int(int(dt["train_death"]) / 10000))
        data["pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[2].amount"] = "0" if dt[
                                                                                                                 "ship_death"] == "0" else str(
            int(int(dt["ship_death"]) / 10000))
        data["pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[3].amount"] = "0" if dt[
                                                                                                                 "passenger_death"] == "0" else str(
            int(int(dt["passenger_death"]) / 10000))
        data["pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[0].amount"] = private_death
        data["pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[1].amount"] = private_death
        data["pagePropertyObj.insuEndDate"] = endDate
        data["pagePropertyObj.insuPeriod"] = "12" if dt["days"] == "1y" else dt["days"].replace("m", "")
        payload = urlencode(data).replace("+", "")
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200 and "pagePropertyObj" in r.text:
            prices = [price["premium"] for price in r.json()["pagePropertyObj"]["liabilityList"]]
            price = Helper.decimalParse(sum(prices))
            data = {
                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            print(data)
            mysql.updatePrice(data)
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("\n/*产品价格更新价格失败:%d*/" % dt["id"])

    def startProcess(self):
        threads = []
        for i in range(10):
            mysql = MysqlClient()
            t = Thread(target=Helper.runProcess, args=(mysql, self.name, self.requestJson))
            t.start()
            threads.append( t )
        for t in threads:
            t.join()
